// pages/apply/evaluate/index.js
const app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		grade: 1, //评分
		arrImgs: [],
		imgDingsun: '', //定损单
		imgXiaoan: '', //销案
    imgChesun: '', //
    imgQingdan:'',
    baseUrl: app.globalData.baseUrl,
    repairArrImgs:[],
    repair_img_urls:''
	},
	onBindStar(e) {
		var index = e.currentTarget.dataset.index;
		this.setData({
			grade: index + 1
		})
  },

	onPreview(e){
		console.log(e)
		var url =  e
		wx.previewImage({
		  current: '', // 当前显示图片的 http 链接
		  urls: [] // 需要预览的图片 http 链接列表
		})
	},
	onUploadDingsun(file, type) {
		let that = this;
		wx.showLoading({
			title: '上传中',
			mask: true
		})

		wx.uploadFile({
			url: app.globalData.baseUrl + '/api/apply/uploadDingSun', //仅为示例，非真实的接口地址
			method: 'POST', //这句话好像可以不用
			header: {
				// 'content-type': 'multipart/form-data',
				"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
				'token': app.globalData.token,
			},
			filePath: file[0].path,
			name: 'file',
			success(res) {
				wx.hideLoading()
				let data = JSON.parse(res.data)
				if (data.status) {

					if (type == 'image') {
						data.data.records.type = 'image'
					} else {
						data.data.records.type = 'pdf'
					}
					that.setData({
						imgDingsun: data.data.records,
					})
					console.log(data.data.records)
				} else {
					wx.showToast({
						title: data.msg,
						icon: 'none',
						duration: 2000
					})
				}

				//do something
			}
		})
		return false;

	},
	onPreview(e){
		console.log(e.currentTarget.dataset.src)
		// var url =  e
		wx.previewImage({
		  current: e.currentTarget.dataset.src, // 当前显示图片的 http 链接
		  urls: [e.currentTarget.dataset.src] // 需要预览的图片 http 链接列表
		})
	},
	onSubmit(e) {
		var that = this;
		var arrImgs = this.data.arrImgs;
		var repairArrImgs = this.data.repairArrImgs;
		wx.showModal({
			title: '提示',
			content: '请您核对提交的信息是否正确',
			confirmColor: '#DC5640',
			success(res) {
				if (res.confirm) {
					wx.showLoading({
						title: '提交中',
						mask: true
					})
					
					wx.request({
						url: app.globalData.baseUrl + '/api/apply/apply',
						method: 'POST',
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'token': app.globalData.token,
						},
						data: {
              "id": that.data.imgDingsun.id? that.data.imgDingsun.id:0,
							"bao_xian_name":  e.detail.value.bao_xian_name,
							"chu_xian_date":  e.detail.value.chu_xian_date,
							"ding_sun_price": parseFloat( e.detail.value.ding_sun_price),
							"car_number":  e.detail.value.car_number,

							"car_jia_number":  e.detail.value.car_jia_number,
							"case_number":  e.detail.value.case_number,

              "ding_sun_url": that.data.imgDingsun.img_url,
							"cancel_case_url": that.data.imgXiaoan,
              "img_urls": arrImgs ? arrImgs.join(',') : '',
              "ocr_id":that.data.imgDingsun.ocr_id,
              
              "bank_account_name":e.detail.value.bank_account_name,
				      "bank_type": e.detail.value.bank_type,
              "bank_card":e.detail.value.bank_card,
              // "repair_list_img_url":that.data.imgQingdan,
              "repaired_urls": repairArrImgs ? repairArrImgs.join(',') : ''
						},
						success: function(res) {
							console.log(res.data.msg)

							wx.hideLoading()
							if (res.data.status) {
								wx.showModal({
									title: "提示",
									content: res.data.msg,
									icon: 'none',
									showCancel: false,
									confirmColor: '#DC5640',
									success(res) {
                    wx.reLaunch({
                      url: '/pages/order/index',
                    })
                    
										// wx.navigateBack()
									}
								})

							} else {
                wx.showModal({
                  title: '提示',
                  content: res.data.msg,
                  success (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                })
								// wx.showToast({
								// 	title: res.data.msg,
								// 	icon: 'none',
								// 	duration: 2000,
								// })
							}
						},
						fail: function() {
							// wx.hideLoading()
							console.log("请求失败")
						}
					})
				} else if (res.cancel) {
					console.log('用户点击取消')
				}
			}
		})

	},
	onUploadGuard(file, type) {
		let that = this;
		let formData = {}
		if (type == 1||type == 3) {
			formData = {
				"module": "order",
				"imgIsCut": "false"
			}
		} else {
			formData = {
				"module": "order",
			}
		}

		wx.showLoading({
			title: '上传中',
			mask: true
		})
		wx.uploadFile({
			url: app.globalData.baseUrl + '/guard/upload', //仅为示例，非真实的接口地址
			method: 'POST', //这句话好像可以不用
			header: {
				'Content-Type': 'Application/x-www-form-urlencoded;charset=utf-8',
				'token': app.globalData.token,
			},
			filePath: file,
			name: 'file',
			formData: formData,
			success(res) {
				wx.hideLoading()
				let data = JSON.parse(res.data)
				if (data.status) {
					if (type == 1) {
						that.setData({
							imgXiaoan: data.data.records.filePath
						})
					} else if(type == 3){
            that.setData({
							imgQingdan: data.data.records.filePath
						})
          }else if(type==2) {
						let arr = that.data.arrImgs;
						arr.push(data.data.records.filePath)
						that.setData({
							arrImgs: arr
						})
					}else if(type==4) {
						let arr = that.data.repairArrImgs;
						arr.push(data.data.records.filePath)
						that.setData({
							repairArrImgs: arr
						})
					}

				} else {
					wx.showToast({
						title: data.msg,
						icon: 'none',
						duration: 2000
					})
				}

				//do something
			}
		})
		return false;

	},
	delImg(e) {
		let index = e.currentTarget.dataset.index;
		let arrs = this.data.arrImgs;
		arrs.splice(index, 1);
		this.setData({
			arrImgs: arrs
		})
  },
  delImg1(e) {
		let index = e.currentTarget.dataset.index;
		let arrs = this.data.repairArrImgs;
		arrs.splice(index, 1);
		this.setData({
			repairArrImgs: arrs
		})
	},
	choseFile() {
		let that = this;
		let data = {}
		wx.showModal({
		  title: '提示',
		  content: '请选择上传格式',
		  cancelText:'PDF',
		  confirmText:'图片',
		  success (res) {
		    if (res.confirm) {
			
				wx.chooseImage({
					count: 1,
					mediaType: ['image'],
					sourceType: ['album', 'camera'],
					maxDuration: 30,
					camera: 'back',
					success(res) {
						let size = res.tempFiles[0].size;
						if (size > 1024 * 1024 * 2) {
							wx.showToast({
								title: '文件过大',
								icon: 'none',
								duration: 2000
							})
							return false
						}
						console.log(res.tempFiles[0].path)
						that.onUploadDingsun(res.tempFiles, 'image')
				
					}
				})
			 
		    } else if (res.cancel) {
		      wx.chooseMessageFile({
		      	count: 1,
		      	type: 'all',
		      	success(res) {
		      		let fileType = res.tempFiles[0].name.split('.')[res.tempFiles[0].name.split('.')
		      			.length - 1];
		      		let size = res.tempFiles[0].size;
		      		if (size > 1024 * 1024 * 2) {
		      			wx.showToast({
		      				title: '文件过大',
		      				icon: 'none',
		      				duration: 2000
		      			})
		      			return false
		      		}
		      		let type = '';
		      		if (res.tempFiles[0].type == 'image') {
		      			type = 'image'
		      		} else if (fileType == 'pdf') {
		      			type = 'pdf'
		      		} else {
		      			wx.showToast({
		      				title: '文件格式错误',
		      				icon: 'none',
		      				duration: 2000
		      			})
		      			return false
		      		}
		      
		      		that.onUploadDingsun(res.tempFiles, type)
		      	}
		      })
		    }
		  }
		})
		
	},
	choseImage(e) {
		let that = this;
		wx.chooseImage({
			count: 1,
			mediaType: ['image'],
			sourceType: ['album', 'camera'],
			maxDuration: 30,
			camera: 'back',
			success(res) {
				let size = res.tempFiles[0].size;
				if (size > 1024 * 1024 * 2) {
					wx.showToast({
						title: '文件过大',
						icon: 'none',
						duration: 2000
					})
					return false
				}
				that.onUploadGuard(res.tempFiles[0].path, 1)


			}
		})
  },
  
	choseImages() {
		let that = this;
		wx.chooseImage({
			count: 6,
			mediaType: ['image'],
			sourceType: ['album', 'camera'],
			maxDuration: 30,
			camera: 'back',
			success(res) {

				if (that.data.arrImgs.length + res.tempFiles.length > 6) {
					wx.showToast({
						title: "最多上传6张",
						icon: 'none',
						duration: 2000
					})
				} else {
					for (var i = 0; i < res.tempFiles.length; i++) {
						that.onUploadGuard(res.tempFiles[i].path, 2)
					}

				}

			}
		})
  },
  
  choseImage1(e) {

		let that = this;
		wx.chooseImage({
			count: 1,
			mediaType: ['image'],
			sourceType: ['album', 'camera'],
			maxDuration: 30,
			camera: 'back',
			success(res) {
				let size = res.tempFiles[0].size;
				if (size > 1024 * 1024 * 2) {
					wx.showToast({
						title: '文件过大',
						icon: 'none',
						duration: 2000
					})
					return false
				}
				that.onUploadGuard(res.tempFiles[0].path, 3)


			}
		})
  },
  
  choseImages1() {
		let that = this;
		wx.chooseImage({
			count: 6,
			mediaType: ['image'],
			sourceType: ['album', 'camera'],
			maxDuration: 30,
			camera: 'back',
			success(res) {

				if (that.data.repairArrImgs.length + res.tempFiles.length > 6) {
					wx.showToast({
						title: "最多上传6张",
						icon: 'none',
						duration: 2000
					})
				} else {
					for (var i = 0; i < res.tempFiles.length; i++) {
						that.onUploadGuard(res.tempFiles[i].path, 4)
					}

				}

			}
		})
  },
	/**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(option){
    //获取通信通道
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', (data)=> {
        //对发送过来的数据进行处理
       
        console.log(data);
        let suffix=data.data.ding_sun_url.split('.');
        suffix=suffix[suffix.length-1];
        let type="pdf"
        if(suffix=='pdf'||suffix=='PDF'){
          type="pdf"
        }else{
          type="image"
        }
        this.setData({
          imgDingsun: {
            id:data.data.id,
            img_url:data.data.ding_sun_url,
            bao_xian_name:data.data.bao_xian_name,
            car_number:data.data.car_number,
            car_jia_number:data.data.car_jia_number,
            ding_sun_price:data.data.ding_sun_price,
            // case_number:data.data.case_number,
            // chu_xian_date:data.data.chu_xian_date,
            bank_account_name:data.data.bank_account_name,
            bank_card:data.data.bank_card,
            bank_type:data.data.bank_type,
            type:type,
            ocr_id:data.data.ocr_id
          },
          imgXiaoan:data.data.cancel_case_url,
          arrImgs:data.data.img_urls,
          repairArrImgs:data.data.repaired_urls
        })
        
      console.log(this.data)
    })
    //向上一页面发送数据
    // eventChannel.emit('acceptDataFromOpenedPage', {data: 'test'});
    // eventChannel.emit('someEvent', {data: 'test'});
  },

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
